//
//  GradientTextLabel.swift
//  SCA
//
//  Created by tjun on 2025/9/21.
//

import UIKit

class GradientTextLabel: UIView {

    private let label = UILabel()
    private let gradientLayer = CAGradientLayer()
    
    let font: UIFont
    var text: String? {
        didSet {
            label.text = text
            label.sizeToFit()
            setNeedsLayout()
        }
    }
    
    var colors: [UIColor]? {
          didSet { updateColors() }
      }

    init(font: UIFont) {
        self.font = font
        super.init(frame: .zero)
        setupUI()
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    private func setupUI() {
        label.textAlignment = .center
        label.font = font
        label.textColor = .white // 占位色
        label.numberOfLines = 0
        addSubview(label)

        gradientLayer.startPoint = CGPoint(x: 0, y: 0.5)
        gradientLayer.endPoint = CGPoint(x: 1, y: 0.5)
        layer.addSublayer(gradientLayer)

        // 使用 label 的 layer 作为 mask 的 **复制**，而不是直接用 label.layer
        let maskLayer = CALayer()
        maskLayer.contentsScale = UIScreen.main.scale
        gradientLayer.mask = maskLayer
    }

    private func updateColors() {
        gradientLayer.colors = colors?.map { $0.cgColor }
    }
        
    override func layoutSubviews() {
        super.layoutSubviews()
        label.frame = bounds
        gradientLayer.frame = bounds

        if let maskLayer = gradientLayer.mask {
            UIGraphicsBeginImageContextWithOptions(label.bounds.size, false, UIScreen.main.scale)
            label.layer.render(in: UIGraphicsGetCurrentContext()!)
            let image = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()
            maskLayer.contents = image?.cgImage
            maskLayer.frame = bounds
        }
    }
}
